<template>
  <div>
    <!-- 图标面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数!" type="warning" :closable="false" show-icon></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="mt15 mb15">
        <el-col>
          <span>选择商品分类： </span>
          <el-cascader
                v-model="selectedKeys"
                :options="categoryList"
                :props="cascaderProps"
                clearable
                @change="cascaderChanged"></el-cascader>
                <!-- :change-on-select="true" -->
        </el-col>
      </el-row>

      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="dynamic">
          <!-- 这里的教程用计算属性，但是因为更简单的是直接用selectedKeys.length -->
          <el-button type="primary" size="mini" class="mb15"
            @click="addDialogVisible = true"
            :disabled="!selectedKeys.length">
            添加参数
          </el-button>
          <el-table :data="tableData.dynamic" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals"
                  :key="index" closable
                  @close="handleClose(index, scope.row.attr_vals)">
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model.trim="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag"
                    size="small" @click="showInput(scope.row)">
                    + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template>
                <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
                <el-button type="danger" size=   "mini" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="static">
          <!-- 这里的教程用计算属性，但是因为更简单的是直接用selectedKeys.length -->
          <el-button type="primary" size="mini" class="mb15"
            @click="addDialogVisible = true"
            :disabled="!selectedKeys.length">
            添加属性
          </el-button>
          <el-table :data="tableData.static" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染Tag标签 -->
                <el-tag v-for="(item, index) in scope.row.attr_vals"
                  :key="index" closable>
                  {{ item }}
                </el-tag>
                <!-- 输入的文本框 -->
                <el-input class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template>
                <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog :title="'添加' + (activeName === 'static' ? '静态属性' : '动态参数')"
      :visible.sync="addDialogVisible" width="50%"
      @close="addDialogClose">
      <!-- 内容主体 -->
      <el-form ref="addRef" :model="addForm" :rules="addRules" label-width="70px" class="add-form">
          <el-form-item :label="activeName === 'static' ? '静态属性' : '动态参数'"
              prop="attr_name" label-width="100px">
              <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
      </el-form>
       <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      categoryList: [], // 商品分类列表
      cascaderProps: { // 指定分类的级联选择器的配置对象
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      selectedKeys: [],
      activeName: 'dynamic', // 激活页签名称
      tableData: {
        dynamic: [],
        static: []
      },

      addDialogVisible: false,
      addForm: {
        attr_name: ''
      }, // 添加参数的表单数据对象
      addRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCategoryList()
  },
  computed: {

  },
  methods: {
    async getCategoryList () {
      // 获取所有商品分类列表
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
        .catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('获取商品分类列表失败！')
      this.$message.success('获取商品分类列表成功！')
      this.categoryList = res.objects
    },
    async cascaderChanged () {
      // 级联选择数据变化触发
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        return
      }

      // 只能选中三级分类
      console.log(this.selectedKeys)

      // 根据所选分类的ID获取对应的静态和动态参数
      const { data: res } = await this.$http.get(
        `categories/${this.selectedKeys[2]}/attributes`
        // { params: { sel: this.activeName } }
      ).catch(err => ({ data: { status: 500, message: err } }))
      console.log(res)
      if (res.status !== 200) return this.$message.error('获取参数列表失败！')
      this.$message.success('获取参数列表成功！')
      res.objects.dynamic.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示隐藏
        item.inputVisible = false
        // 文本框的值
        item.inputValue = ''
      })
      res.objects.static.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示隐藏
        item.inputVisible = false
        // 文本框的值
        item.inputValue = ''
      })
      this.tableData = res.objects
    },
    handleTabsClick () {
      console.log(this.activeName)
    },
    addDialogClose () {
      this.$refs.addRef.resetFields()
    },
    handleClose (index, vals) {
      vals.splice(index, 1)
    },
    handleInputConfirm (tag) {
      // tag中文本框失去焦点或者按下Enter键
      tag.inputVisible = false
      if (!tag.inputValue) return
      tag.attr_vals.push(tag.inputValue)
      tag.inputValue = ''
    },
    showInput (tag) {
      // 点击按钮展示输入文本对话框
      tag.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.mt15{
  margin-top: 15px;
}

.mb15{
  margin-bottom: 15px;
}

.mr15{
  margin-right: 15px;
}

.el-tag {
  margin: 10px;
}

.input-new-tag{
  width: 120px;
}
</style>
